<template>
  <div>
    <el-card>
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="basic">
          <el-form :model="info" ref="genFormRef" :rules="rules">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="实体类名称" prop="className">
                  <el-input placeholder="请输入" v-model="info.className" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="作者" prop="functionAuthor">
                  <el-input placeholder="请输入" v-model="info.functionAuthor" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="packageName">
                  <template #label>
                    生成包路径
                    <el-tooltip content="生成在哪个java包下，例如 com.ruoyi.system" placement="top">
                      <el-icon><question-filled /></el-icon>
                    </el-tooltip>
                  </template>
                  <el-input v-model="info.packageName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实体描述" prop="tableComment">
                  <el-input type="textarea" :rows="2" v-model="info.tableComment"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="genType">
                  <template #label>
                    生成代码方式
                    <el-tooltip content="默认为zip压缩包下载，也可以自定义生成路径" placement="top">
                      <el-icon><question-filled /></el-icon>
                    </el-tooltip>
                  </template>
                  <el-radio v-model="info.genType" label="0">zip压缩包</el-radio>
                  <el-radio v-model="info.genType" label="1">自定义路径</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="info.genType == '1'">
                <el-form-item prop="genPath">
                  <template #label>
                    自定义路径
                    <el-tooltip content="填写磁盘绝对路径(到src为止)，若不填写，则生成到当前Web项目下" placement="top">
                      <el-icon><question-filled /></el-icon>
                    </el-tooltip>
                  </template>
                  <el-input v-model="info.genPath">
                    <template #append>
                      <el-dropdown>
                        <el-button type="primary">
                          最近路径快速选择
                          <i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="info.genPath = '/'">恢复默认的生成基础路径</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="字段信息" name="columnInfo">
          <div>
            <hot-table :data="columns" :rowHeaders="true" :contextMenu="true" language="zh-CN" :headerTooltips="true"
              :maxCols="8" :columnSorting="true" :renderAllRows="true" :persistentState="true" ref="hotTable"
              :manualRowMove="true" :beforeColumnMove="beforeColumnMove" :afterChange="afterChange" startRows="4"
              height="400" :manualColumnMove="true" :nestedHeaders="[
                [{ label: '名称', colspan: 1 }, { label: '类型', colspan: 1 }, { label: '是否必填', colspan: 1 }, { label: '描述', colspan: 1 }, { label: '示例值', colspan: 1 }, { label: '对应java类型', colspan: 1 }, { label: 'java字段名', colspan: 1 }, { label: '@JsonProperty名', colspan: 1 }],
              ]" :columns="[
  { data: 'name' },
  {
    data: 'type',

  },
  {
    data: 'notBlank',
    type: 'checkbox',
  },
  { data: 'columnComment', trimWhitespace: true },
  { data: 'example' },
  {
    data: 'javaType',
    type: 'autocomplete',
    source: javaTypeList,
    strict: true,
    allowInvalid: false,

  },
  {
    data: 'javaField',
  },
  {
    data: 'jsonProperty',
  },
]" licenseKey="non-commercial-and-evaluation">
            </hot-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-form label-width="100px">
        <div style="text-align: center; margin-left: -100px; margin-top: 100px">
          <el-button type="primary" @click="submitForm('gen')">生成</el-button>
          <el-button type="primary" @click="submitForm()">预览</el-button>
          <el-button @click="close()">抖音登陆</el-button>
        </div>
      </el-form>
    </el-card>
    <!-- 预览界面 -->
    <el-dialog :title="preview.title" v-model="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))" :key="value">
          <el-link :underline="false" icon="DocumentCopy" v-copyText="value" v-copyText:callback="copyTextSuccess"
            style="float: right">&nbsp;复制</el-link>
          <pre>{{ value }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  previewDomainTable, genDomainTable
} from '@/api/tool/gen'
import { HotTable } from '@handsontable/vue3'
import { registerAllModules } from 'handsontable/registry'
import 'handsontable/dist/handsontable.full.css'
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n'
import { tansParams } from '@/utils/ruoyi'
import { camelCase } from '@/utils/index'
const { proxy } = getCurrentInstance();
registerLanguageDictionary(zhCN)
// register Handsontable's modules
registerAllModules()
// 表单校验
const rules = ref({
  packageName: [
    { required: true, message: '请输入生成包路径', trigger: 'blur' },
  ],
  moduleName: [
    { required: true, message: '请输入生成模块名', trigger: 'blur' },
  ],
  functionName: [
    { required: true, message: '请输入生成功能名', trigger: 'blur' },
  ],
  tableComment: [{ required: false, message: '请输入实体类描述', trigger: 'blur' }],
  className: [{ required: true, message: '请输入实体类名称', trigger: 'blur' }],
  functionAuthor: [{ required: true, message: '请输入作者', trigger: 'blur' }],
})
const activeName = ref('columnInfo')
const javaTypeList = ref([
  'Long',
  'String',
  'Integer',
  'Double',
  'BigDecimal',
  'Date',
  'Boolean',
  'Object'
])
const preview = ref({
  open: false,
  title: '代码预览',
  data: {},
  activeName: 'tiktok-domain.java',
})
const info = ref({
  className: '',
  moduleName: '',
  packageName: '',
  functionAuthor: '',
  functionName: '@ ',
  tableName: '1',
  businessName: '@',
  tableComment: '',
  genPath: '',
})
const columns = ref([{}])
onMounted(() => {
  let localInfo = JSON.parse(localStorage.getItem('info'))
  if (localInfo) {
    info.value = localInfo
    Object.assign(columns.value, localInfo.columns)
  }
})
const submitForm = (genFlag) => {
  let mergeInfo = Object.assign(info.value, { columns: columns.value }) // 合并对象]
  if (genFlag) {
    genDomainTable(mergeInfo).then((response) => {
      proxy.$modal.msgSuccess('生成成功')
      //将info存入本地
      localStorage.setItem('info', JSON.stringify(mergeInfo))
    })
  } else {
    previewDomainTable(mergeInfo).then((response) => {
      preview.value.data = response.data
      preview.value.open = true
      preview.value.activeName = 'tiktok-domain.java'
      //将info存入本地
      localStorage.setItem('info', JSON.stringify(mergeInfo))
    })
  }

}
/** 复制代码成功 */
function copyTextSuccess() {
  proxy.$modal.msgSuccess('复制成功')
}

const close = () => {
  //打开新页面新地址
  const client = {
    client_key: "awxehxmkgkgzxlxm",
    response_type: "code",
    scope: "user_info,trial.whitelist,fans.check",
    optionalScope: null,
    redirect_uri: "https://139.155.96.238",
    state: null
  }
  window.open("https://open.douyin.com/platform/oauth/connect/?" + tansParams(client))
}
const beforeColumnMove = (
  movedColumns,
  finalIndex,
  dropIndex,
  movePossible
) => {
  if (movedColumns > 3) {
    return false;
  }
  return true
}
const afterChange = (changes, source) => {
  console.log(changes, source)
  changes?.forEach(([row, prop, oldValue, newValue]) => {
    newValue = newValue.trim()
    columns.value[row][prop] = newValue
    if (prop == 'type' && newValue != null) {
      let curValue = newValue.slice(0, 3).toLowerCase()
      columns.value[row]['javaType'] = javaTypeList.value.filter(item => { return item.toLowerCase().startsWith(curValue) || item == 'Object' })[0]
    }
    if (prop == 'name') {
      columns.value[row]['javaField'] = camelCase(newValue)
      columns.value[row]['jsonProperty'] = newValue
    }
  })
  console.log(columns.value)

}
</script>
<style lang="scss">
.htMenu.htContextMenu.handsontable {
  z-index: 9999;
}
</style>
